package com.wingscode.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wingscode.common.annotation.SysLog;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.R;
import com.wingscode.common.validator.ValidatorUtils;
import com.wingscode.common.validator.group.AddGroup;
import com.wingscode.common.validator.group.UpdateGroup;
import com.wingscode.modules.common.entity.AgentEntity;
import com.wingscode.modules.common.entity.ServiceUsageRecordEntity;
import com.wingscode.modules.common.entity.UserEntity;
import com.wingscode.modules.common.service.AgentService;
import com.wingscode.modules.common.service.ServiceUsageRecordService;
import com.wingscode.modules.common.service.UserService;
import com.wingscode.modules.sys.controller.AbstractController;
import com.wingscode.modules.sys.entity.*;
import com.wingscode.modules.sys.form.InquiryQueryForm;
import com.wingscode.modules.sys.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 招标、供应
 *
 * @author yan
 */
@RestController
@RequestMapping("/app/inquiry")
public class InquiryController extends AbstractController {
	@Autowired
	private InquiryService inquiryService;
	@Autowired
	private InquiryLinkService inquiryLinkService;
	@Autowired
	private OfferPriceService offerPriceService;
	@Autowired
	private SearchLogService searchLogService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private UserService userService;
	@Autowired
	private ServiceUsageRecordService serviceUsageRecordService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private BuildQualService buildQualService;


	/**
	 * 市场列表信息
	 */
	@PostMapping("/marketList")
	public R marketList(@RequestBody InquiryQueryForm form){
//		if (form.getLoginUserId() == null)
//			return R.error("loginUserId为空");

		// 检索内容不为空时，保存检索历史
		saveSearchLog(form);

		PageUtils page = inquiryService.queryPage(form);

		return R.ok().put("page", page);
	}

	/**
	 * 主页列表信息
	 */
	@PostMapping("/mainList")
	public R mainList(@RequestBody InquiryQueryForm form){
//		if (form.getContent() != null && !form.getContent().isEmpty() && form.getLoginUserId() == null)
//			return R.error("loginUserId为空");

		// 检索内容不为空时，保存检索历史
		saveSearchLog(form);

		PageUtils page = inquiryService.mainList(form);

		return R.ok().put("page", page);
	}

	/**
	 * 我的招标、我的供应list
	 */
	@PostMapping("/myList")
	public R myList(@RequestBody InquiryQueryForm form){
		if (form.getLoginUserId() == null)
			return R.error("loginUserId为空");

		// 员工看自己的招标，管理员看整个公司的招标
		UserEntity user = userService.getById(form.getLoginUserId());
		if (user != null) {
			if (user.getRole() == 99)
				form.setLoginUserId(null);

			form.setAgentId(user.getAgentId());
		}

		PageUtils page = inquiryService.myList(form);

		return R.ok().put("page", page);
	}

	/**
	 * 我的报价list
	 */
	@PostMapping("/myOfferPriceList")
	public R myOfferPriceList(@RequestBody InquiryQueryForm form){
		if (form.getLoginUserId() == null)
			return R.error("loginUserId为空");

		PageUtils page = inquiryService.myOfferPriceList(form);

		return R.ok().put("page", page);
	}

	/**
	 * 我的-招标详情、供应详情
	 */
	@GetMapping("/info")
	public R info(@RequestParam Integer id, @RequestParam Integer loginUserId){
		if (id == null)
			return R.error("id为空");
		if (loginUserId == null)
			return R.error("loginUserId为空");

		InquiryEntity entity = inquiryService.getInfo(id);
		if (entity != null) {
			// 获得报价信息
			List<OfferPriceEntity> list = new ArrayList<>();
			// 判断当前招标是否为登录用户的
			if (entity.getUserId() == loginUserId) {
				// 登录用户的招标，显示所有报价信息
				list = offerPriceService.getListByInquiryId(entity.getId());
			} else {
				// 非登录用户的招标，显示当前登录用户的报价信息
				OfferPriceEntity offerPriceEntity = offerPriceService.getByUserId(entity.getId(), loginUserId);
				list.add(offerPriceEntity);
			}

			entity.setOfferPriceList(list);
		}

        return R.ok(200, entity);
	}

	/**
	 * 我的报价-报价详情
	 */
	@GetMapping("/myOfferPriceInfo")
	public R myOfferPriceInfo(@RequestParam Integer inquiryId, @RequestParam Integer userId){
		if (inquiryId == null)
			return R.error("inquiryId为空");
		if (userId == null)
			return R.error("userId为空");

		InquiryEntity entity = inquiryService.getInfo(inquiryId);
		if (entity != null) {
			// 获得报价信息
			OfferPriceEntity offerPriceEntity = offerPriceService.getByUserId(entity.getId(), userId);
			entity.setOfferPrice(offerPriceEntity);
		}

		return R.ok(200, entity);
	}

	/**
	 * 成交记录-招标详情
	 */
	@GetMapping("/chatInquiryInfo")
	public R chatInquiryInfo(@RequestParam Integer id, @RequestParam Integer loginUserId){
		if (id == null)
			return R.error("id为空");
		if (loginUserId == null)
			return R.error("loginUserId为空");

		InquiryEntity entity = inquiryService.getInfo(id);
		if (entity != null) {
			// 获得报价信息
			OfferPriceEntity offerPriceEntity = new OfferPriceEntity();
			if (loginUserId == -1)
				offerPriceEntity = offerPriceService.getById(entity.getChatOfferId());
			else
				offerPriceEntity = offerPriceService.getOne(
						new QueryWrapper<OfferPriceEntity>()
								.eq("inquiry_id", id)
								.eq("user_id", loginUserId)
				);

			entity.setOfferPrice(offerPriceEntity);

			List<OfferPriceEntity> priceList = offerPriceService.getListByInquiryId(entity.getId());
			entity.setOfferPriceList(priceList);
		}

		return R.ok(200, entity);
	}

	/**
	 * 保存招标信息
	 */
	@PostMapping("/save")
	public R save(@RequestBody InquiryEntity entity){
		if(entity.getUserId() == null)
			return R.error("userId为空");
		if (entity.getAgentId() == null)
			return R.error("agentId为空");

		if (entity.getLinkList() != null && entity.getLinkList().size() > 0) {
			for (InquiryLinkEntity link : entity.getLinkList()) {
				if (link.getBuildQualNameId() != null && link.getGrade() != null) {
					BuildQualEntity buildQual = buildQualService.getByGrade(link.getBuildQualNameId(), link.getGrade());
					if (buildQual == null)
						return R.error("当前选中的资质不存在");
				}
			}
		}
		if (entity.getNewLinkList() != null && entity.getNewLinkList().size() > 0) {
			for (InquiryLinkEntity link : entity.getNewLinkList()) {
				if (link.getBuildQualNameId() != null && link.getGrade() != null) {
					BuildQualEntity buildQual = buildQualService.getByGrade(link.getBuildQualNameId(), link.getGrade());
					if (buildQual == null)
						return R.error("当前选中的资质不存在");
				}
			}
		}
		ValidatorUtils.validateEntity(entity, AddGroup.class);

		// 获得当前企业信息
		AgentEntity agent = agentService.getById(entity.getAgentId());
		if (agent != null) {
			if (agent.getState() != 1)
				return R.error("企业审核未通过，暂时无法发布信息");
			if (entity.getType() != 4 && agent.getQualNum() <= 0)
				return R.error("当前无企业资质发布次数");
			if (entity.getType() == 4 && agent.getPersonnelNum() <= 0)
				return R.error("当前无人才猎聘发布次数");
		}

		inquiryService.saveInquiry(entity);

		if (agent != null) {
			// 发布次数减一
			if (entity.getType() == 4) {
				// 人才猎聘
				agent.setPersonnelNum(agent.getPersonnelNum() - 1);
			} else {
				// 其他
				agent.setQualNum(agent.getQualNum() - 1);
			}
			agent.setUpdateTime(new Date());

			agentService.updateById(agent);

			// 添加增值服务使用记录信息
			ServiceUsageRecordEntity usageRecord = new ServiceUsageRecordEntity();
			usageRecord.setAgentId(entity.getAgentId());
			usageRecord.setUserId(entity.getUserId());
			usageRecord.setCreateTime(new Date());
			if (entity.getType() == 4)
				usageRecord.setTitle("人才猎聘信息发布");
			else
				usageRecord.setTitle("企业资质信息发布");
			usageRecord.setNum(1);
			usageRecord.setType(0);

			serviceUsageRecordService.save(usageRecord);
		}


		return R.ok();
	}

	/**
	 * 修改招标信息
	 */
	@PostMapping("/update")
	public R update(@RequestBody InquiryEntity entity){
		if(entity.getUserId() == null)
			return R.error("userId为空");
		if (entity.getAgentId() == null)
			return R.error("agentId为空");
		ValidatorUtils.validateEntity(entity, UpdateGroup.class);

		inquiryService.updateInquiry(entity);

		return R.ok();
	}

	/**
	 * 删除招标信息
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] Ids){
		// 删除
		inquiryService.deleteBatch(Ids);
		// 删除link
		if (Ids != null && Ids.length > 0) {
			for (Long id : Ids) {
				inquiryLinkService.deleteByInquiry(id.intValue());
			}
		}

		return R.ok();
	}

	/**
	 * 修改招标状态(0-重新发布 1-已完成)
	 */
	@PostMapping("/changeState")
	public R changeState(@RequestBody InquiryEntity entity) {
		if (entity.getId() == null)
			return R.error("id为空");
		if (entity.getState() == null)
			return R.error("state为空");

		InquiryEntity inquiry = inquiryService.getById(entity.getId());
		if (inquiry != null) {
			inquiry.setState(entity.getState());
			inquiry.setUpdateTime(new Date());

			inquiryService.updateById(inquiry);

			// 已完成时，对应报价状态也为已完成
			if(entity.getState() == 1) {
				if (inquiry.getChatOfferId() != null) {
					OfferPriceEntity offerPrice = offerPriceService.getById(inquiry.getChatOfferId());
					if (offerPrice != null) {
						offerPrice.setState(2);
						offerPrice.setUpdateTime(new Date());

						offerPriceService.updateById(offerPrice);
					}
				}
			}
		}

		return R.ok();
	}

	/**
	 * 立即沟通-改变招标信息
	 */
	@PostMapping("/chooseChat")
	public R chooseChat(@RequestBody Map<String, Object> params) {
		Integer inquiryId = null, chatOfferId = null;
		if (!params.containsKey("chatOfferId"))
			return R.error("chatOfferId为空");
		if (!params.containsKey("inquiryId"))
			return R.error("inquiryId为空");

		inquiryId = Integer.parseInt(params.get("inquiryId").toString());
		chatOfferId = Integer.parseInt(params.get("chatOfferId").toString());

		InquiryEntity inquiry = inquiryService.getById(inquiryId);
		if (inquiry != null) {
			inquiry.setChatOfferId(chatOfferId);
			inquiry.setUpdateTime(new Date());
			inquiry.setChatOfferTime(new Date());

			inquiryService.updateById(inquiry);
		}

		// 其他报价信息失效
		List<OfferPriceEntity> offerList = offerPriceService.list(
				new QueryWrapper<OfferPriceEntity>()
						.eq("inquiry_id", inquiryId)
		);
		if (offerList != null && offerList.size() > 0) {
			for (OfferPriceEntity offer : offerList) {
				if (offer.getId() == chatOfferId)
					// 沟通中
					offer.setState(1);
				else
					// 已失效
					offer.setState(3);
				offer.setUpdateTime(new Date());

				offerPriceService.updateById(offer);
			}
		}

		return R.ok();
	}

	/**
	 * 清除搜索历史
	 */
	@GetMapping("/deleteSearchLog")
	public R deleteSearchLog(@RequestParam Integer userId) {
		if (userId == null)
			return R.error("userId为空");

		searchLogService.deleteByUserId(userId);

		return R.ok();
	}

	/**
	 * 获得搜索历史
	 */
	@GetMapping("getSearchLog")
	public R getSearchLog(@RequestParam Integer userId) {
		if (userId == null)
			return R.error("userId为空");

		List<SearchLogEntity> list = searchLogService.list(
				new QueryWrapper<SearchLogEntity>()
						.eq("user_id", userId)
						.orderByDesc("create_time")
		);

		return R.ok(200, list);
	}

	/**
	 * 保存搜索历史
	 */
	private void saveSearchLog(InquiryQueryForm form) {
		if (form.getContent() != null && !form.getContent().isEmpty()) {
			// 判断当前检索内容是否已存在
			List<SearchLogEntity> list = searchLogService.list(
					new QueryWrapper<SearchLogEntity>()
							.eq("user_id", form.getLoginUserId())
							.eq("content", form.getContent())
			);
			// 保存检索关键字
			if (list == null || list.size() == 0) {
				SearchLogEntity entity = new SearchLogEntity();
				entity.setUserId(form.getLoginUserId());
				entity.setContent(form.getContent());
				entity.setCreateTime(new Date());

				searchLogService.save(entity);
			}
		}
	}

	/**
	 * 获得城市
	 */
	@GetMapping("getAreaList")
	public R getAreaList() {
		List<RegionEntity> list = regionService.list(
				new QueryWrapper<RegionEntity>()
						.eq("pid", 0)
						.orderByAsc("sort")
		);
		if (list != null && list.size() > 0) {
			for (RegionEntity entity : list) {
				List<RegionEntity> child = regionService.list(
						new QueryWrapper<RegionEntity>()
								.eq("pid", entity.getId())
								.orderByAsc("sort")
				);

				entity.setChildList(child);
			}
		}

		return R.ok(200, list);
	}
}
